package com.iflytek.jzcpx.procuracy.tools.elle;

import java.io.IOException;
import java.util.List;

import cn.hutool.http.HttpRequest;
import com.google.common.collect.Lists;
import com.iflytek.jzcpx.procuracy.common.result.Result;
import com.iflytek.jzcpx.procuracy.common.util.IdWokerUtil;
import com.iflytek.jzcpx.procuracy.common.util.JSONUtil;
import com.iflytek.jzcpx.procuracy.tools.common.enums.ToolsContstants;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 要素抽取 客户端
 *
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2019-08-06 19:42
 */
public class ElleClient {
    private static final Logger logger = LoggerFactory.getLogger(ElleClient.class);

    /** ocr 接口地址 */
    private final String SERVER_URL;

    public ElleClient(String server, String path) {
        this.SERVER_URL = StringUtils.removeEnd(server, "/") + StringUtils.prependIfMissing(path, "/");
        logger.info("创建 Elle 客户端, 接口地址: {}", SERVER_URL);
    }

    /**
     * 请求要素抽取引擎
     *
     * @param textTypeEnum 待抽取的文件类型
     * @param fileContent  文件内容
     *
     * @return
     *
     * @throws IOException
     */
    public Result<String> request(ElleTextTypeEnum textTypeEnum, String fileContent) throws IOException {
        ElleParam param = buildParam(textTypeEnum, fileContent);
        String body = JSONUtil.toStrDefault(param);
        String resp = HttpRequest.post(SERVER_URL).body(body).header("Content-Type", "application/json; charset=UTF-8")
                .timeout(ToolsContstants.ENGINE_REQUEST_TIMEEOUT).execute().body();

        return Result.success(JSONUtil.getProp(JSONUtil.toJsonNode(resp), "tag", String.class));
    }

    public static ElleParam buildParam(ElleTextTypeEnum typeEnum, String fileContent) {
        ElleParam param = new ElleParam();
        param.setTrackId(String.valueOf(IdWokerUtil.nextId()));
        ElleParam.Text text = param.getTexts().get(0);
        text.setType(typeEnum.toString());
        text.setContent(fileContent);
        return param;
    }

    @Data
    public static class ElleParam {
        /** 1:只抽取内容， 2：抽取内容及位置 */
        private String protocol_level = "2";

        private String trackId;

        /** 案由， aktq: 案卡提取 */
        private String usrId = "aktq";

        /** 关系抽取开关 */
        private boolean rlt_switch = true;

        /** 待解析文本 */
        private List<Text> texts = Lists.newArrayList(new Text());

        @Data
        public class Text {
            /** 文本内容 */
            private String content;

            /** 文本类型 */
            private String type;
        }
    }
}
